<template>
  <div class="pay-order-container">
    <h2 class="page-title">订单支付</h2>
    
    <div v-if="loading" class="loading-container">
      <el-skeleton style="width: 100%" :rows="10" animated />
    </div>
    
    <div v-else>
      <el-card class="order-info">
        <template #header>
          <div class="card-header">
            <span>订单信息</span>
            <el-tag v-if="orderInfo" :type="getOrderStatusType(orderInfo.status)">
              {{ getOrderStatusText(orderInfo.status) }}
            </el-tag>
          </div>
        </template>
        
        <div class="order-details" v-if="orderInfo">
          <p class="order-number">订单号：{{ orderInfo.orderNo }}</p>
          <p class="order-time">创建时间：{{ orderInfo.createTime }}</p>
          <p class="order-amount">支付金额：<span class="price">¥ {{ orderInfo.totalAmount }}</span></p>
          
          <div class="order-items">
            <h4>订单内容</h4>
            <el-table :data="orderInfo.items || []" border stripe>
              <el-table-column label="活动名称" prop="eventName" min-width="200" />
              <el-table-column label="票种" prop="ticketName" />
              <el-table-column label="单价" prop="price">
                <template #default="scope">
                  <span class="price">¥ {{ scope.row.price }}</span>
                </template>
              </el-table-column>
              <el-table-column label="数量" prop="quantity" width="80" />
              <el-table-column label="小计" prop="subtotal">
                <template #default="scope">
                  <span class="subtotal">¥ {{ (scope.row.price * scope.row.quantity).toFixed(2) }}</span>
                </template>
              </el-table-column>
            </el-table>
          </div>
          
          <div class="payment-info" v-if="orderInfo.status === 'unpaid'">
            <h4>支付方式</h4>
            <div class="payment-methods">
              <el-radio-group v-model="paymentMethod">
                <el-radio label="alipay">
                  <img src="@/assets/payment/alipay.png" class="payment-icon" alt="支付宝" />
                  支付宝
                </el-radio>
                <el-radio label="wechat">
                  <img src="@/assets/payment/wechat.png" class="payment-icon" alt="微信支付" />
                  微信支付
                </el-radio>
              </el-radio-group>
            </div>
            
            <div class="payment-actions">
              <el-button type="primary" size="large" @click="payNow" :loading="paying">
                立即支付 ¥{{ orderInfo.totalAmount }}
              </el-button>
              <el-button type="text" @click="goBack">取消支付</el-button>
            </div>
          </div>
          
          <div class="payment-success" v-else-if="orderInfo.status === 'paid'">
            <el-result icon="success" title="支付成功" sub-title="您的订单已支付成功，可在订单列表中查看详情">
              <template #extra>
                <el-button type="primary" @click="goToOrderList">查看订单</el-button>
                <el-button @click="goToEventList">继续购票</el-button>
              </template>
            </el-result>
          </div>
          
          <div class="payment-cancelled" v-else-if="orderInfo.status === 'cancelled'">
            <el-result icon="error" title="订单已取消" sub-title="该订单已取消，无法继续支付">
              <template #extra>
                <el-button type="primary" @click="goToEventList">继续购票</el-button>
                <el-button @click="goToOrderList">查看订单</el-button>
              </template>
            </el-result>
          </div>
        </div>
        
        <div v-else class="no-order">
          <el-empty description="未找到订单信息" />
        </div>
      </el-card>
      
      <el-card class="order-tips" v-if="orderInfo && orderInfo.status === 'unpaid'">
        <div class="timer" v-if="countdown > 0">
          <el-alert type="warning" :closable="false">
            <div class="countdown">
              <i class="el-icon-time"></i>
              <span>请在 {{ formatCountdown(countdown) }} 内完成支付，超时订单将自动取消</span>
            </div>
          </el-alert>
        </div>
        
        <h4>温馨提示</h4>
        <ul class="tips-list">
          <li>支付成功后，系统将自动为您生成电子票</li>
          <li>电子票可在 "我的票券" 中查看</li>
          <li>如遇支付问题，请联系客服</li>
        </ul>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getOrderDetail, payOrder, getOrderStatus } from '@/api/order'

const route = useRoute()
const router = useRouter()
const orderId = route.query.orderId

// 订单信息
const orderInfo = ref(null)
// 加载状态
const loading = ref(true)
// 支付方式
const paymentMethod = ref('alipay')
// 支付中状态
const paying = ref(false)
// 倒计时(毫秒) - 默认15分钟
const countdown = ref(15 * 60 * 1000)
// 定时器
let timer = null
// 状态检查定时器
let statusCheckTimer = null

// 获取订单详情
const fetchOrderDetail = async () => {
  if (!orderId) {
    ElMessage.error('未指定订单ID')
    router.push('/front/event/list')
    return
  }
  
  loading.value = true
  try {
    const res = await getOrderDetail(orderId)
    if (res.code === 200 && res.data) {
      orderInfo.value = res.data
      
      // 如果订单未支付，启动倒计时
      if (orderInfo.value.status === 'unpaid') {
        // 根据创建时间计算剩余支付时间
        const createTime = new Date(orderInfo.value.createTime).getTime()
        const now = Date.now()
        const expireTime = createTime + (15 * 60 * 1000) // 15分钟过期
        
        if (now < expireTime) {
          countdown.value = expireTime - now
          startCountdown()
        } else {
          // 订单已过期
          countdown.value = 0
          orderInfo.value.status = 'cancelled'
        }
      }
    } else {
      ElMessage.error('获取订单详情失败')
    }
  } catch (error) {
    console.error('获取订单详情出错:', error)
    ElMessage.error('获取订单详情失败')
  } finally {
    loading.value = false
  }
}

// 立即支付
const payNow = async () => {
  if (paying.value) return
  
  if (!paymentMethod.value) {
    ElMessage.warning('请选择支付方式')
    return
  }
  
  paying.value = true
  try {
    const res = await payOrder(orderId)
    if (res.code === 200) {
      // 启动订单状态轮询
      ElMessage.success('支付请求已提交')
      startStatusCheck()
    } else {
      ElMessage.error(res.msg || '支付请求失败')
    }
  } catch (error) {
    console.error('支付订单出错:', error)
    ElMessage.error('支付失败，请稍后重试')
  } finally {
    paying.value = false
  }
}

// 启动倒计时
const startCountdown = () => {
  if (timer) clearInterval(timer)
  
  timer = setInterval(() => {
    countdown.value -= 1000
    if (countdown.value <= 0) {
      clearInterval(timer)
      // 订单过期，更新状态
      orderInfo.value.status = 'cancelled'
      ElMessage.warning('订单已超时，请重新下单')
    }
  }, 1000)
}

// 定时检查订单状态
const startStatusCheck = () => {
  if (statusCheckTimer) clearInterval(statusCheckTimer)
  
  // 每3秒检查一次订单状态，最多检查10次
  let checkCount = 0
  
  statusCheckTimer = setInterval(async () => {
    checkCount++
    try {
      const res = await getOrderStatus(orderId)
      if (res.code === 200 && res.data) {
        // 如果状态变为已支付，停止检查
        if (res.data.status === 'paid') {
          orderInfo.value = res.data
          clearInterval(statusCheckTimer)
          ElMessage.success('支付成功')
        }
      }
    } catch (error) {
      console.error('检查订单状态出错:', error)
    }
    
    // 最多检查10次
    if (checkCount >= 10) {
      clearInterval(statusCheckTimer)
    }
  }, 3000)
}

// 格式化倒计时
const formatCountdown = (ms) => {
  const minutes = Math.floor(ms / 60000)
  const seconds = Math.floor((ms % 60000) / 1000)
  return `${minutes}分${seconds < 10 ? '0' : ''}${seconds}秒`
}

// 获取订单状态类型
const getOrderStatusType = (status) => {
  switch (status) {
    case 'paid': return 'success'
    case 'unpaid': return 'warning'
    case 'cancelled': return 'danger'
    default: return 'info'
  }
}

// 获取订单状态文本
const getOrderStatusText = (status) => {
  switch (status) {
    case 'paid': return '已支付'
    case 'unpaid': return '待支付'
    case 'cancelled': return '已取消'
    default: return '未知状态'
  }
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 前往订单列表
const goToOrderList = () => {
  router.push('/front/user/orders')
}

// 前往活动列表
const goToEventList = () => {
  router.push('/front/event/list')
}

// 页面加载时获取数据
onMounted(() => {
  fetchOrderDetail()
})

// 组件销毁时清除定时器
onUnmounted(() => {
  if (timer) clearInterval(timer)
  if (statusCheckTimer) clearInterval(statusCheckTimer)
})
</script>

<style scoped>
.pay-order-container {
  max-width: 1000px;
  margin: 20px auto;
  padding: 20px;
}

.page-title {
  margin-bottom: 20px;
  color: #303133;
}

.loading-container {
  padding: 20px;
}

.order-info, .order-tips {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.order-details {
  margin-bottom: 20px;
}

.order-number, .order-time {
  color: #606266;
  line-height: 1.8;
}

.order-amount {
  margin: 10px 0;
  font-size: 16px;
  font-weight: bold;
}

.price, .subtotal {
  color: #f56c6c;
  font-weight: bold;
}

.order-items {
  margin: 20px 0;
}

.payment-info {
  margin-top: 30px;
}

.payment-methods {
  margin: 20px 0;
}

.payment-icon {
  width: 24px;
  height: 24px;
  margin-right: 5px;
  vertical-align: middle;
}

.payment-actions {
  margin-top: 30px;
  display: flex;
  justify-content: center;
  gap: 20px;
}

.countdown {
  font-size: 14px;
  font-weight: bold;
}

.tips-list {
  padding-left: 20px;
  line-height: 1.8;
  color: #606266;
}
</style> 